package com.example.myapplication;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS)!= PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.READ_CONTACTS},1);
        }else {
            readContacts();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,  String[] permissions,  int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (grantResults.length>0){
            if (grantResults[0]==PackageManager.PERMISSION_GRANTED){
                readContacts();
            }else {
                Toast.makeText(this,"无权限",Toast.LENGTH_SHORT).show();
            }
        }
    }
    private void readContacts(){
        Uri contentUri = ContactsContract.Contacts.CONTENT_URI;
        Cursor query = getContentResolver().query(contentUri, null, null, null, null);
        int count=query.getCount();
        Log.d("MainActivity", "readContacts: "+count);
        while (query.moveToNext()){
            int id = query.getInt(query.getColumnIndex("_id"));
            String name = query.getString(query.getColumnIndex("display_name"));
            String phoneNumber="";
            int number = query.getInt(query.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
            if (number>0){
                Cursor query1 = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                        ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=?",
                        new String[]{Integer.toString(id)}, null);
                query1.moveToFirst();
                phoneNumber=query1.getString(query1.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

            }
            Log.d("MainActivity","获取姓名："+name);
            Log.d("MainActivity","获取号码个数："+number);
            Log.d("MainActivity","获取号码："+phoneNumber);

        }
    }
}